package cn.com.bsoft.mobile.controller


import cn.com.bsoft.mobile.model.AppVersionRsp
import cn.com.bsoft.mobile.model.DeviceType
import cn.com.bsoft.mobile.model.QueryAppVersionReq
import cn.com.bsoft.mobile.service.AppVersionService
import cn.com.bsoft.mobile.service.MobileAppService
import cn.net.xyan.blossom.core.service.ConfigService
import cn.net.xyan.blossom.core.utils.absoluteURL
import cn.net.xyan.blossom.kotlin.AllOpen
import cn.net.xyan.blossom.kotlin.StatusAndMessageError
import com.dd.plist.PropertyListParser
import org.springframework.beans.factory.annotation.Autowired
import org.springframework.http.HttpEntity
import org.springframework.http.MediaType
import org.springframework.stereotype.Controller
import org.springframework.http.HttpHeaders
import org.springframework.web.bind.annotation.*
import java.io.ByteArrayOutputStream


@Controller
@AllOpen
@RequestMapping("/app")
class VersionController{

    @Autowired
    lateinit var appVersion:MobileAppService

    @Autowired
    lateinit var configService: ConfigService

    @Autowired
    lateinit var versionService: AppVersionService

    @RequestMapping("/versions",produces = arrayOf(MediaType.APPLICATION_JSON_UTF8_VALUE))
    @ResponseBody
    fun queryVersion(@RequestBody req:QueryAppVersionReq):List<AppVersionRsp>{
        return versionService.queryVersion(req)
    }

    @RequestMapping("/version/{type}/{appID}/{version:.+}")
    @ResponseBody
    fun version(@PathVariable type:String,@PathVariable appID:String,@PathVariable version:String):HttpEntity<ByteArray>{

        val version = versionService.queryVersion(type,appID,version)?:throw StatusAndMessageError("没有发现version:$version")
        val suffix = when(type){
            DeviceType.Android.value -> "apk"
            DeviceType.iOS.value -> "ipa"
            else -> ""
        }
        val fileName = "$appID.${version.version}.$suffix"
        val header = HttpHeaders()
        header.contentType = MediaType("application", suffix)
        header.set("Content-Disposition", "inline; filename=$fileName")
        header.contentLength = version.archive?.data?.size?.toLong()?:0L

        return HttpEntity(version.archive?.data?:throw StatusAndMessageError("data is null"), header)
    }

    @RequestMapping("/inHouse/{appID}/{version}.plist",produces = arrayOf("application/x-plist"))
    @ResponseBody
    fun plist(@PathVariable("appID") appID:String,@PathVariable("version") version:String):HttpEntity<ByteArray>{
        val version = versionService.queryVersion(DeviceType.iOS.value,appID,version)?:throw StatusAndMessageError("没有发现version:$version")

        val nsObject = versionService.convert2plist(version)

        val output = ByteArrayOutputStream()
        PropertyListParser.saveAsXML(nsObject, output)

        val bytes = output.toByteArray()

        val fileName = "$appID-$version.plist"
        val header = HttpHeaders()
        header.contentType = MediaType("application", "x-plist")
        //header.set("Content-Disposition", "inline; filename=$fileName")
        header.contentLength = bytes.size.toLong()

        return HttpEntity(bytes, header)
    }

    @RequestMapping("/inHouse/{appID:.+}")
    fun inHouseInstall(@PathVariable("appID") appID:String,@RequestParam(required = false,value = "version")version: String?):String{
        var req = QueryAppVersionReq()
        req.nativeID = appID
        req.version = version
        val result = versionService.queryVersion(req)
        if (result.isEmpty()) throw StatusAndMessageError("$appID 没有可用版本")
        val first = result.first()

        if(DeviceType.iOS == first.type) {

            val appRoot = configService.queryValue(ConfigService.KEYAppRoot)
            val url = "$appRoot/app/inHouse/$appID/${first.version}.plist"

            return "redirect:itms-services://?action=download-manifest&url=$url"
        }else{
            val url = absoluteURL("/app/version/${DeviceType.Android.value}/$appID/${first.version}")
            return "redirect:$url"
        }
    }
}